# Contributor: Leo <thinkabit.ukim@gmail.com>
# Contributor: Maxim Karasev <begs@disroot.org>
# Maintainer: Maxim Karasev <begs@disroot.org>
pkgname=fpc
pkgver=3.2.2
pkgrel=2
pkgdesc="Free Pascal Compiler"
url="http://freepascal.org"
# Build fails on ppc64le with compiler segfault
arch="x86_64 aarch64 armv7 armhf x86" # limited by fpc-stage0
license="GPL-2.0-or-later AND LGPL-2.1-or-later"
makedepends="fpc-bootstrap"
subpackages="$pkgname-doc"
source="https://downloads.sourceforge.net/sourceforge/freepascal/fpcbuild-$pkgver.tar.gz"
options="!check" # no tests
builddir="$srcdir/fpcbuild-$pkgver"

# FPC is self-hosting and requires itself to build. We use fpc-stage0 to build
# fpc initially and then use fpc itself. Therefore we make fpc provide
# fpc-bootstrap as well and prioritize it over fpc-stage0
provides="fpc-bootstrap"
provider_priority=100 # highest

# libpas2jslib.so contains textrels on some arches
case "$CARCH" in
	x86|armv7|armhf) options="$options textrels";;
esac

prepare() {
	default_prepare

	# Use correct linker path for produced binaries
	sed -i -e "s,/lib64/ld-linux-x86-64\.so\..,/lib/ld-musl-x86_64.so.1," \
		-e "s,/lib/ld-linux\.so\..,/lib/ld-musl-i386.so.1," \
		-e "s,/lib/ld-linux-aarch64\.so\..,/lib/ld-musl-aarch64.so.1," \
		-e "s,/lib/ld-linux-armhf\.so\..,/lib/ld-musl-armhf.so.1," \
		-e "s,/lib64/ld64\.so\..,/lib/ld-musl-powerpc64le.so.1," \
		"$builddir"/fpcsrc/compiler/systems/t_linux.pas

	# Strip out any unsupported instructions
	find "$builddir"/fpcsrc/rtl/linux -type f -print0 |
		xargs -0 sed -i '/libc_csu/d'
}

build() {
	cd fpcsrc/compiler
	fpcmake -Tall
	cd ../
	make build NOGDB=1
}

package() {
	make install \
		NOGDB=1 \
		PREFIX="$pkgdir"/usr \
		INSTALL_MANDIR="$pkgdir"/usr/share/man

	# Create a symlink needed for fpc to find compiler
	ln -s /usr/lib/fpc/"$pkgver"/ppc* "$pkgdir"/usr/bin

	# Install configuration
	mkdir -p "$pkgdir"/etc
	"$pkgdir"/usr/lib/fpc/"$pkgver"/samplecfg \
		"$pkgdir"/usr/lib/fpc/"$pkgver" "$pkgdir"/etc

	# Strip pkgdir name from configs
	find "$pkgdir"/etc/ -type f -exec sed -i "s|$pkgdir||g" {} \;
}

sha512sums="
75889bb54adc70a6e2cbd291476b9b12d61c8f943a05b7d16d2024de3215c935465ff43b1400c412e128e260c7f49a9c66e35c21f86cb866e671b5b60a282d82  fpcbuild-3.2.2.tar.gz
"
